package com.pisolution.scheduler.runtime.master.dispatcher.host;

import com.pisolution.scheduler.core.tuple.Tuple3;
import com.pisolution.scheduler.datasource.group.WorkerGroupMapper;
import com.pisolution.scheduler.remote.command.Command;
import com.pisolution.scheduler.remote.utils.Host;

import com.google.common.base.Preconditions;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 以随机的方式选取工作节点.
 *
 * @author sora
 * @version 0.1.0
 */
@Component
public class RandomHostManager implements HostManager {
    /** 用于读取可选工作节点列表. */
    private final WorkerGroupMapper group;

    /** 用于生成随机数. */
    private final Random random;

    // -------------------------------------------------------------------------------------------------
    //  初始化
    // -------------------------------------------------------------------------------------------------

    public RandomHostManager(final WorkerGroupMapper group) {
        this.group = group;
        this.random = new Random();
    }

    // -------------------------------------------------------------------------------------------------
    //  节点选择
    // -------------------------------------------------------------------------------------------------

    @Override
    public Host select(Tuple3<Host, Command, String> context) {
        // 1. 读取可用工作节点.
        final String[] servers = this.group.queryServerByName(context.field3).split(",");

        // 2. 如果无可用节点 则放弃选择 判定为系统异常.
        Preconditions.checkArgument(
            ObjectUtils.isNotEmpty(servers),
            "Could not find any worker server for selection."
        );

        // 3. 随机选取一个节点并返回.
        return Host.of(servers[this.random.nextInt(servers.length)]);
    }
}
